package com.cunfang.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;



import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Tools {

	/**
	 * 随机生成六位数验证码
	 * 
	 * @return
	 */
	public static int getRandomNum() {
		Random r = new Random();
		return r.nextInt(900000) + 100000;// (Math.random()*(999999-100000)+100000)
	}

	/**
	 * 检测字符串是否不为空(null,"","null")
	 * 
	 * @param s
	 * @return 不为空则返回true，否则返回false
	 */
	public static boolean notEmpty(String s) {
		return s != null && !"".equals(s) && !"null".equals(s);
	}

	/**
	 * 检测字符串是否为空(null,"","null")
	 * 
	 * @param s
	 * @return 为空则返回true，不否则返回false
	 */
	public static boolean isEmpty(String s) {
		return s == null || "".equals(s) || "null".equals(s);
	}

	/**
	 * 字符串转换为字符串数组
	 * 
	 * @param str
	 *            字符串
	 * @param splitRegex
	 *            分隔符
	 * @return
	 */
	public static String[] str2StrArray(String str, String splitRegex) {
		if (isEmpty(str)) {
			return null;
		}
		return str.split(splitRegex);
	}

	/**
	 * 用默认的分隔符(,)将字符串转换为字符串数组
	 * 
	 * @param str
	 *            字符串
	 * @return
	 */
	public static String[] str2StrArray(String str) {
		return str2StrArray(str, ",\\s*");
	}

	/**
	 * 按照yyyy-MM-dd HH:mm:ss的格式，日期转字符串
	 * 
	 * @param date
	 * @return yyyy-MM-dd HH:mm:ss
	 */
	public static String date2Str(Date date) {
		return date2Str(date, "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 按照yyyy-MM-dd HH:mm:ss的格式，字符串转日期 java.sql.Date()
	 * 
	 * @param date
	 * @return
	 */
	public static java.sql.Date str2SqlDate(String date) {
		if (notEmpty(date)) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if (!isValidDate(date) && date.length() == 9) {
				date = date + " 00:00:00";
			}

			try {
				java.sql.Date sqlDimissionDate = new java.sql.Date(sdf.parse(
						date).getTime());
				return sqlDimissionDate;
				// return sdf.parse(date);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			return new java.sql.Date(System.currentTimeMillis());
		} else {
			return null;
		}
	}

	/**
	 * 
	 * @author ZhuHongKai
	 * @Description: 判断日期格式
	 * @date 2016年9月23日
	 */
	public static boolean isValidDate(String str) {
		boolean convertSuccess = true;
		// 指定日期格式为四位年/两位月份/两位日期，注意yyyy/MM/dd区分大小写；
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			// 设置lenient为false.
			// 否则SimpleDateFormat会比较宽松地验证日期，比如2007/02/29会被接受，并转换成2007/03/01
			format.setLenient(false);
			format.parse(str);
		} catch (ParseException e) {
			// e.printStackTrace();
			// 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
			convertSuccess = false;
		}
		return convertSuccess;
	}

	/**
	 * 按照yyyy-MM-dd HH:mm:ss的格式，字符串转日期 java.util.Date()
	 * 
	 * @param date
	 * @return
	 */
	public static Date str2Date(String date) {
		if (notEmpty(date)) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
				return sdf.parse(date);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			return new Date();
		} else {
			return null;
		}
	}

	/**
	 * 按照参数format的格式，日期转字符串
	 * 
	 * @param date
	 * @param format
	 * @return
	 */
	public static String date2Str(Date date, String format) {
		if (date != null) {
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			return sdf.format(date);
		} else {
			return "";
		}
	}

	/**
	 * 把时间根据时、分、秒转换为时间段
	 * 
	 * @param StrDate
	 */
	public static String getTimes(String StrDate) {
		String resultTimes = "";

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		java.util.Date now;

		try {
			now = new Date();
			java.util.Date date = df.parse(StrDate);
			long times = now.getTime() - date.getTime();
			long day = times / (24 * 60 * 60 * 1000);
			long hour = (times / (60 * 60 * 1000) - day * 24);
			long min = ((times / (60 * 1000)) - day * 24 * 60 - hour * 60);
			long sec = (times / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);

			StringBuffer sb = new StringBuffer();
			// sb.append("发表于：");
			if (hour > 0) {
				sb.append(hour + "小时前");
			} else if (min > 0) {
				sb.append(min + "分钟前");
			} else {
				sb.append(sec + "秒前");
			}

			resultTimes = sb.toString();
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return resultTimes;
	}

	/**
	 * 写txt里的单行内容
	 * 
	 * @param filePath
	 *            文件路径
	 * @param content
	 *            写入的内容
	 */
	public static void writeFile(String fileP, String content) {
		String filePath = String.valueOf(Thread.currentThread()
				.getContextClassLoader().getResource(""))
				+ "../../"; // 项目路径
		filePath = (filePath.trim() + fileP.trim()).substring(6).trim();
		if (filePath.indexOf(":") != 1) {
			filePath = File.separator + filePath;
		}
		try {
			OutputStreamWriter write = new OutputStreamWriter(
					new FileOutputStream(filePath), "utf-8");
			BufferedWriter writer = new BufferedWriter(write);
			writer.write(content);
			writer.close();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 验证邮箱
	 * 
	 * @param email
	 * @return
	 */
	public static boolean checkEmail(String email) {
		boolean flag = false;
		try {
			String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
			Pattern regex = Pattern.compile(check);
			Matcher matcher = regex.matcher(email);
			flag = matcher.matches();
		} catch (Exception e) {
			flag = false;
		}
		return flag;
	}

	/**
	 * 验证手机号码
	 * 
	 * @param mobiles
	 * @return
	 */
	public static boolean checkMobileNumber(String mobileNumber) {
		boolean flag = false;
		try {
			Pattern regex = Pattern
					.compile("^(((13[0-9])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8})|(0\\d{2}-\\d{8})|(0\\d{3}-\\d{7})$");
			Matcher matcher = regex.matcher(mobileNumber);
			flag = matcher.matches();
		} catch (Exception e) {
			flag = false;
		}
		return flag;
	}

	/**
	 * 读取txt里的单行内容
	 * 
	 * @param filePath
	 *            文件路径
	 */
	public static String readTxtFile(String fileP) {
		try {

			String filePath = String.valueOf(Thread.currentThread()
					.getContextClassLoader().getResource(""))
					+ "../../"; // 项目路径
			filePath = filePath.replaceAll("file:/", "");
			filePath = filePath.replaceAll("%20", " ");
			filePath = filePath.trim() + fileP.trim();
			if (filePath.indexOf(":") != 1) {
				filePath = File.separator + filePath;
			}
			String encoding = "utf-8";
			File file = new File(filePath);
			if (file.isFile() && file.exists()) { // 判断文件是否存在
				InputStreamReader read = new InputStreamReader(
						new FileInputStream(file), encoding); // 考虑到编码格式
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while ((lineTxt = bufferedReader.readLine()) != null) {
					return lineTxt;
				}
				read.close();
			} else {
				System.out.println("找不到指定的文件,查看此路径是否正确:" + filePath);
			}
		} catch (Exception e) {
			System.out.println("读取文件内容出错");
		}
		return "";
	}

	/**
	 * 获取汉字的拼音码
	 * 
	 * @param 传入的字符
	 * @return 返回 拼音码
	 * */
	public static String getPyCode(String strVaule) {
		// 汉字区位码
		int li_SecPosValue[] = { 1601, 1637, 1833, 2078, 2274, 2302, 2433,
				2594, 2787, 3106, 3212, 3472, 3635, 3722, 3730, 3858, 4027,
				4086, 4390, 4558, 4684, 4925, 5249, 5590 };
		// 存放国标一级汉字不同读音的起始区位码对应读音
		char lc_FirstLetter[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J',
				'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'W', 'X',
				'Y', 'Z' };
		// 二级字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JJXXGLLJSTGSHJQLZFKCGNNNSZFDEQFHBSAQTGYLBXMMYGSZLDYDQMJJRGBJ"
				+ "TKGDHGKBLQKBDMBYLXWCXYTTYBKMRTJZXQJBHLMHMJJZMQASLDCYXYQDLQCAFYWYXQHZ";

		java.lang.String sreturn = "";
		for (int j = 0; j < strVaule.length(); j++) {
			String stemp = strVaule.substring(j, j + 1);
			byte[] by = stemp.getBytes();
			if (by.length == 1) {
				sreturn = sreturn + stemp;
			} else {
				int ia = 96 + (int) by[0]; // 区码
				int ib = 96 + (int) by[1]; // 位码
				int in = ia * 100 + ib;
				if (in > 1600 && in < 5590) {
					for (int i = 0; i < 24; i++) {
						if (in < li_SecPosValue[i]) {
							sreturn = sreturn + lc_FirstLetter[i - 1];
							break;
						}
					}
				} else {
					ioffset = (ia - 56) * 94 + ib - 1;
					if (ioffset >= 0 && ioffset <= 3007) {
						sreturn = sreturn
								+ ls_SecondSecTable.substring(ioffset,
										ioffset + 1);
					}
				}
			}
			sreturn = sreturn.toUpperCase();
		}
		return sreturn;

	}

	/**
	 * @功能：判断目标值是否符合正则表达式表达式
	 * @作者：RC
	 * @日期：2016-10-04
	 * */
	public static boolean CheckRegex(Object obj, String reg) {
		String str = String.valueOf(obj);
		return str.matches(reg);
	}

	/**
	 * 得到当前日期拼接的随机数
	 * */
	public static String GetCurrDateInfo() {
		SimpleDateFormat time = new SimpleDateFormat("yyyyMMddHHmmssms");
		Random r = new Random();
		int in = r.nextInt(100) + 100;
		return time.format(new Date()) + in;
	}

	

	/**
	 * 把pagedata转成 xml
	 * */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static String PageDataToXml(PageData pd) {
		String str = "";
		if (pd == null) {
			return str;
		}
		Map.Entry me;
		Object obj = null;
		String strTem = "";
		String key = "";
		Iterator it = pd.entrySet().iterator();
		while (it.hasNext()) {
			me = (Map.Entry) it.next();
			obj = me.getValue();
			key = me.getKey().toString();
			strTem = "";
			if (obj instanceof PageData) {
				strTem = PageDataToXml((PageData) obj);
				strTem = "<" + key + ">" + strTem + "</" + key + ">";
			} else if (obj instanceof List) {
				strTem = ListToXml((List) obj, key);
				// strTem = "<" + key + ">" + strTem + "</" + key + ">";
			} else {
				if (obj != null && obj.toString().length() > 0) {
					strTem = "<" + key + ">" + (obj == null ? "" : obj) + "</"
							+ key + ">";
				}

			}
			str += strTem;
		}
		return str;
	}

	/**
	 * 把list转成 xml
	 * */
	public static String ListToXml(List<PageData> list, String key) {
		String str = "";
		for (int i = 0; i < list.size(); i++) {
			str += "<" + key + ">" + PageDataToXml(list.get(i)) + "</" + key
					+ ">";
		}
		return str;
	}

	

	
	public static byte[] md5Byte(String encryptStr) throws Exception {
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(encryptStr.getBytes("UTF-8"));
		return md.digest();
	}

	/**
	 * 如果为“” null 就返回null
	 * */
	public static Object isNull(Object obj) {
		if (obj == null || obj.toString().length() == 0) {
			return null;
		} else {
			return obj;
		}
	}

	

	

	public static void main(String[] args) throws Exception {
		// GetAllianEncryptPassword();
		
	}

}
